import json
import random
from datetime import datetime

from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.csrf import csrf_exempt

from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import BootStrapModelForm


class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = models.Order
        # fields = "__all__"
        exclude = ["oid", "admin"]


@csrf_exempt
def order_list(request):
    queryset = models.Order.objects.all().order_by('-id')
    form = OrderModelForm()
    page_object = Pagination(request, queryset)
    context = {
        "form": form,
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, "order.html", context)


@csrf_exempt
def order_add(request):
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999))
        form.instance.admin_id = request.session["info"]["id"]  # 当前登陆的用户的id，送session获取
        form.save()
        # print("数据保存成功！")
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))
    # print(type(form.errors.get_json_data()))
    data_dict = {"status": False, "error": form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))


def order_delete_1(request, nid):
    row_object = models.Order.objects.filter(id=nid).get()

    # 无数据
    if not row_object:
        msg_error = "数据不存在！"
        return render(request, 'error.html', {"msg_error": msg_error})

    # 无权限，当前用户只允许删除自己创建的订单
    a = request.session["info"]["id"]  # 获取当前登陆id
    # print('#', a, type(a))
    b = row_object.admin_id  # 获取订单创建者id
    # print("#", b, type(row_object))
    if not a == b:  # 无权限
        msg_error = "无权限删除！"
        return render(request, 'error.html', {"msg_error": msg_error})
    models.Order.objects.filter(id=nid).delete()
    return redirect('/order/list/')


def order_delete(request):
    """ 删除订单 """
    uid = request.GET.get('uid')
    # print('obj.id #:', uid)

    # 无权限，当前用户只允许删除自己创建的订单
    loginid = request.session["info"]["id"]  # 获取当前登陆id
    # print('loginid #:', loginid)
    adminid = models.Order.objects.filter(id=uid).get().admin_id
    # print('adminid #:', adminid)

    if not loginid == adminid:  # 无权限
        return JsonResponse({"status": False, "error": "删除失败，无删除权限"})

    # 无数据
    exists = models.Order.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({"status": False, "error": "删除失败，订单不存在"})

    models.Order.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


def order_detail(request):
    """ 根据uid,获得订单信息 """
    uid = request.GET.get("uid")
    row_object = models.Order.objects.filter(id=uid).first()

    # 方式1
    """
    # 从数据库中获得数据 row_object是对象，当前所有的数据
    row_object = models.Order.objects.filter(id=uid).first()
    
    result = {
        "status": True,
        "data": {
            "title": row_object.title,
            "price": row_object.price,
            "status": row_object.status,
        }
    }
    if not row_object:
        return JsonResponse({"status": False, 'error': "数据不存在"})
    return JsonResponse(result)
    """
    # 方式2
    # 从数据库中获得数据 row_object是字典，当前所有的数据
    row_dict = models.Order.objects.filter(id=uid).values("title","price","status" ).first()
    if not row_dict:
        return JsonResponse({"status": False, 'error': "数据不存在"})
    result={
        "status":True,
        "data":row_dict
    }
    return JsonResponse(result)

@csrf_exempt
def order_edit(request):
    """ 编辑订单 """
    uid=request.GET.get("uid")
    row_object=models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({"status":False,"tips":"数据不存在"})
    form=OrderModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({"status":True})
    return JsonResponse({"status":False,'error':form.errors})

